<?php

/**
* @property CustomerType $CustomerType
* @property Customer $Customer
* @property CustomerShopperGroup $CustomerShopperGroup
* @property Gift $Gift
* @property Cashier $Cashier
* @property Group $Group
* @property User $User
* @property OpenSesion $OpenSesion
* @property OnsiteSesion $OnsiteSesion 
* @property Package $Package
* @property Ticket $Ticket
* @property Trainer $Trainer
* @property Option $Option
* @property Discount $Discount
* @property Report $Report
* @property Course $Course
* @property Language $Language
* @property Emstraining $EmstrainingComponent
* @property MailboxComponent $Mailbox
* @property SearchComponent $Search
* @property SendMailComponent $SendMail
* @property $UserAccessComponent UserAccess
*/
App::uses('Controller', 'Controller');
App::uses('Security', 'Utility');
App::uses('Folder', 'Utility');
App::uses('File', 'Utility');
class AppController extends Controller {
    public $components = array('RequestHandler', 'Session', 'Auth',"UserAccess",'Zend',"Emstraining","Sms");    
    public $helpers = array('Loyalty');
    public $vouchers_path=null;
    public $qrcode_path = null;
    public function beforeFilter() {
        parent::beforeFilter();
        $this->vouchers_path = APP.'webroot'.DS.'files'.DS.'vouchers'.DS;
        $this->qrcode_path =  APP.'webroot'.DS.'files'.DS.'qrcodes'.DS;
        if(!is_dir($this->vouchers_path)) {
            $folder = new Folder();
            $folder->create($this->vouchers_path);
        }
        if(!is_dir($this->qrcode_path)) {
            $folder = new Folder();
            $folder->create($this->qrcode_path);
        }
        $this->Auth->autoRedirect = true;
        $this->loadModel("Gift");
        $this->loadModel('Customer');
        
        $gift = $this->Gift->find();
        if(isset($this->params['prefix'])&&($this->params['prefix']=='admin')){
            $this->layout='admin';
        }else{
            $this->layout='default';
        }
        //pr($this);die;
        if ($this->here=="customer_login") {
            //$this->Auth->loginAction = array('controller' => 'customers', 'action' => 'login','admin'=>false);
            $this->setCustomerLogin();
        }elseif($this->here=='admin'){
        //    $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login','admin'=>true);
            $this->setAdminLogin();
        }elseif ($this->here == 'cashier') {
            $this->setCashierLogin();
        }
        
        if ($this->Auth->user()) {
            $this->check_user_permission();
            $this->set("current_user",  $this->Auth->user());
        }
        //$this->set("user",$user);       
        if ($this->Auth->user("indentify")=="cashier" && $this->params['controller'] != 'cashiers') {
            $this->Session->setFlash("You don't have permission to access this page");
            $this->redirect(array('controller'=>'cashiers','action'=>'index'));
        }
        if($this->Auth->user("indentify")=="admin" && $this->params['prefix']!='admin' && $this->params['action'] != "logout"){
            if($this->params['prefix']!='mypdf' && $this->params['action'] != "image_print"){
                $this->Session->setFlash("This is not place for you !");
                $this->redirect(array('controller'=>'users','action'=>'index','admin'=>true));
            }
        }
        if($this->Auth->user("indentify")=="customer"){
            $current_user = $this->Customer->read(null,$this->Auth->user('id'));
            $this->set("current_customer",  $current_user);
        }
        Configure::write('current_controller', $this->name);
        $this->Auth->allow("cashier_info",'get_voucher_gift','send_mobilecode','verify_code','verification','captcha','cashier_login','sell_voucher','change_gift','gifts_vouchers_list','add_gift','deduct_gift',"display","register",'print','save_to_file','barcode_content','content_view','login','logout','get_city_list','question_form','process','print_voucher', 'enquiry', 'help');
        $absolute_path = Router::url('/', true);
        $this->set('js_absolute_path', $absolute_path);
    }
    public function setAdminLogin() {
        $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login','admin'=>true);
        $this->Auth->logoutRedirect = "/";
        $this->Auth->userModel = 'User';
    }
    public function setCustomerLogin() {
        $this->Auth->userModel = 'Customer';
        $this->Auth->loginAction = array('controller' => 'customers', 'action' => 'login','admin'=>false);
        $this->Auth->logoutRedirect = "/";
    }
    public function setCashierLogin() {
        $this->Auth->userModel = 'Cashier';
        $this->Auth->loginAction = array('controller' => 'cashiers', 'action' => 'login','admin'=>false);
        $this->Auth->logoutRedirect = "/";
    }
    public function check_user_permission(){
        App::import('Model', 'User');
        if($this->Auth->user('id')&&$this->Auth->user('indentify')=='admin'){
            if(isset($this->params['prefix'])&&($this->params['prefix']=='admin')&&(!$this->RequestHandler->isAjax())){
                $controller = $this->params['controller'];
                $action = $this->params['action'];
                $action = str_replace('admin_', "", $action);
                if($this->Auth->user('role_id')!=User::ADMINISTRATOR){
                    $check = $this->UserAccess->check_access($controller,$action);
                    if($action=='setting'){
                        $check = $this->UserAccess->check_access('users','view_setting');
                    }
                    if($check==0){
                        $redirect = $this->UserAccess->get_first_redirect();
                        if(!empty($redirect)){
                            $this->Session->setFlash('You don\'t have permission to do that action ');
                            $this->redirect($this->referer($redirect));
                        }else{
                            $this->Session->destroy();
                            $this->Session->setFlash('You don\'t have permission to access this page ');
                            $this->redirect("/");
                        }
                    }
                    $this->set('user_permissions',  $this->UserAccess->get_user_permission_list());
                }
            }
        }elseif($this->Auth->user('id') && !$this->params['prefix'] && ($this->Auth->user('indentify')=='customer' ||$this->Auth->user('indentify')=='cashier')){
            
        }elseif($this->Auth->user('id') && $this->params['prefix']=="mypdf"){
            
        }else{
            $this->Session->destroy();
            $this->Session->setFlash('You don\'t have permission to access this page ');
            $this->redirect("/");
        }
    }
    public function print_voucher($voucher_id,$mode="F") {
        $this->loadModel("Voucher");
        $gift = $this->Voucher->read(null, $voucher_id);
        $this->Zend->writeGiftCode(WWW_ROOT.'files/vouchers/'.$gift['Voucher']['code'].'.png',$gift['Voucher']['code']);
        $this->set('gift', $gift);
        $html = $this->render("/Elements/voucher",false);
        //echo $html;die;
        //$host = Configure::read("code_url");
        /*$host = WWW_ROOT;
        $html = "<table  cellpadding = '5' cellspacing = '5' class='report' width='20%'>
            <tr>
                <th>Code</th>
                <td><img src='$host/files/vouchers/{$voucher['Voucher']['code']}.png'/></td>
            </tr>
            <tr>
                <th>Value</th>
                <td>{$voucher['Voucher']['value']}</td>
            </tr>
            <tr>
                <th>Expired date</th>
                <td>{$voucher['Voucher']['expired_date']}</td>
            </tr>
        </table>";*/
        $this->Emstraining->writePdf($this->vouchers_path."{$gift['Voucher']['code']}",$html,$mode);
        return true;
        //$this->loadModel("Voucher");
        //$file =$this->requestAction(array('controller'=>'vouchers','action'=>'print','mypdf'=>true,$voucher_id,"D"));
        //$file = file_get_contents(Router::url(array('controller'=>'vouchers','action'=>'print','mypdf'=>true,$voucher_id,"D"), true));
        //echo $file;die;
        //  return true;
    }
    public function print_qrcode($code) {
        $this->Zend->writeQrcode($this->qrcode_path."$code.png",$code);
        return true;
    }
    public function send_sms($phone,$code){
        $success =FALSE;
        $sms = $this->Sms->text_message($phone,'Loyalty',"Your verification code : $code     - Loyalty");
        if($sms['result']=='success'){
            $success = TRUE;
        }
        return $success;
    }
}